﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace System
{
    public static class XmlExt
    {
        public static XmlAttribute CreateAttribute(this XmlDocument doc, string name, object value)
        {
            XmlAttribute a = doc.CreateAttribute(name);
            a.Value = value.AsString();
            return a;
        }
        public static void AppendAttribute(this XmlNode node, string name, object value)
        {
            node.Attributes.Append(node.OwnerDocument.CreateAttribute(name, value));
        }
        public static string GetAttributeValue(this XmlNode node, string name)
        {
            if (node.Attributes != null && node.Attributes[name] != null)
                return node.Attributes[name].Value;
            return null;
        }
        public static XmlElement SelectSingleElement(this XmlNode node, string path)
        {
            return node.SelectSingleNode(path) as XmlElement;
        }
        public static XmlElement AppendChildElement(this XmlNode parent, string child, string value = null, bool onlyIfNotExist = true)
        {
            XmlElement el = null;
            el = parent.SelectSingleElement(child);
            XmlDocument doc = null;
            if (parent is XmlDocument)
                doc = (XmlDocument)parent;
            else
                doc = parent.OwnerDocument;

            if (el == null || !onlyIfNotExist)
            {
                el = doc.CreateElement(child);
                if (value != null)
                    el.AppendChildTextElement(value);
                parent.AppendChild(el);
            }
            return el;
        }
        
        public static XmlText AppendChildTextElement(this XmlNode parent, string value)
        {
            XmlText el = null;
            XmlDocument doc = null;
            if (parent is XmlDocument)
                doc = (XmlDocument)parent;
            else
                doc = parent.OwnerDocument;

            el = doc.CreateTextNode(value);
            parent.AppendChild(el);
            return el;
        }
        public static string ToFormatedString(this XmlDocument document)
        {
            string xml = string.Empty;
            using (StringWriter strWriter = new StringWriter())
            {
                using (XmlTextWriter xmlWriter = new XmlTextWriter(strWriter))
                {
                    xmlWriter.Formatting = Formatting.Indented;
                    xmlWriter.IndentChar = '\t';
                    xmlWriter.Indentation = 1;
                    document.WriteTo(xmlWriter);
                    xml = strWriter.GetStringBuilder().ToString();
                }
            }
            return xml;
        }
    }
}
